package com.gxa.medical.controller;

import com.gxa.medical.exception.BusinessException;
import com.gxa.medical.exception.ExceptionCode;
import com.gxa.medical.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
@RestController
@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Throwable.class)
    public Map<String, Object> exceptionHandeler(Exception e) throws Exception {
        JsonResult jsonResult=new JsonResult();
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            jsonResult.setCode(businessException.getExceptionCode().getCode());
            jsonResult.setMsg(businessException.getExceptionCode().getMsg());
            return jsonResult.getResultMap();
        } else {
            //获取当前系统时间并格式化成yyyy-MM-dd
            String fomatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            //把系统异常定义到一个指定的文件目录下
            String path = "d:" + File.separator + "log" + File.separator + "error" + fomatDate + ".log";
            File file = new File(path);
            //判断该文件是否存在,不存在则创建
            if (!file.exists()) {
                file.createNewFile();
            }
            //记录到指定文件中
            OutputStream OutputStream = new FileOutputStream(file, true);
            OutputStreamWriter writer = new OutputStreamWriter(OutputStream, "UTF8");
            StringBuilder builder = new StringBuilder();
            builder.append("--------------------------------------------------------\n");
            builder.append("异常类型: ").append(e.toString()).append("\n");
            builder.append("异常原因: ").append(e.getMessage()).append("\n");
            for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                builder.append(stackTraceElement.toString()).append("\n");
            }
            builder.append("--------------------------------------------------------\n");
            writer.write(builder.toString());
            writer.flush();
            writer.close();
            //给前端反馈信息
            jsonResult.setCode(ExceptionCode.SERVER_FAILED.getCode());
            jsonResult.setMsg(ExceptionCode.SERVER_FAILED.getMsg());
            return jsonResult.getResultMap();
        }
    }
}
